﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Http
{
    public static partial class HttpHelper
    {
        public static string ToParams(this NameValueCollection paras)
        {
            if (paras == null)
            {
                return string.Empty;
            }
            var p = new StringBuilder();
            foreach (string key in paras.AllKeys)
            {
                p.Append(key).Append("=").Append(Uri.EscapeDataString(paras[key] ?? "")).Append("&");
            }
            //p.Remove(p.Length - 1, 1);
            p.Length = p.Length - 1;
            return p.ToString();
        }

        public static string ToParams(this IEnumerable<KeyValuePair<string,string>> paras)
        {
            if (paras==null)
            {
                return string.Empty;
            }
            var p = new StringBuilder();
            foreach (var item in paras)
            {
                p.Append(item.Key).Append("=").Append(Uri.EscapeDataString(item.Value ?? "")).Append("&");
            }
            //p.Remove(p.Length - 1, 1);
            p.Length = p.Length - 1;
            return p.ToString();
        }

        public static string ToParams(this object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            var p = new StringBuilder();
            var type = obj.GetType();
            object value;
            foreach (var item in type.GetProperties())
            {
                value = item.GetValue(obj);
                if (value!=null)
                {
                    p.Append(item.Name).Append("=").Append(Uri.EscapeDataString(item.GetValue(obj).ToString())).Append("&");
                }
            }
            //p.Remove(p.Length - 1, 1);
            p.Length = p.Length - 1;
            return p.ToString();
        }

    }
}
